package com.lxp.design.shop.order.service;

import com.lxp.design.shop.order.entity.User;
import com.lxp.design.shop.order.kafka.sender.KafkaSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LaiXiaoPeng
 * @version 1.0
 * @date 2021/7/19 11:43
 */
@Service
@Slf4j
public class PersonService {
    @Autowired
    private KafkaSender kafkaSender;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Value("${spring.kafka.topic.test}")
    private String topic;

    public void sendKafkaMsg(String msg) {
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>");
        kafkaSender.sendMsg(topic, "TEST", msg);
    }

    public void redisTest() {
        //键值对
        redisTemplate.opsForValue().set("k1", 1);
//        log.info("12");
        log.info("k1:{}", redisTemplate.opsForValue().getAndSet("k1", 2));
        log.info("k1 to 2:{}", redisTemplate.opsForValue().get("k1"));
        //list
        redisTemplate.opsForList().leftPush("list2", "jjk");
//        log.info(redisTemplate);
        log.info(redisTemplate.opsForList().range("list1", 0, -1).toString());
        //乐观锁实现
        redisTemplate.opsForValue().set("money", 100);
        redisTemplate.watch("money");
        while (true) {
            redisTemplate.multi();
            redisTemplate.opsForValue().increment("money", 100);
            List<Object> result = redisTemplate.exec();
            if (!result.isEmpty()) {
                log.info("数据版本一致，修改成功");
                redisTemplate.unwatch();
                break;
            } else {
                log.info("数据版本不一致，修改失败，解锁重置");
                redisTemplate.unwatch();
                redisTemplate.watch("money");
            }
        }
        //测试对象序列化
        redisTemplate.opsForValue().set("user", new User("lxp", 23));
        log.info(redisTemplate.opsForValue().get("user").toString());
    }
}
